package com.example.luyao.myapplication;

import android.Manifest;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.ParcelUuid;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ListView;
import android.widget.Toast;

import com.junkchen.blelib.BleService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class BluetoothActivity extends AppCompatActivity implements BleService.OnLeScanListener,
        BleService.OnServicesDiscoveredListener {
    private final static String TAG = Constants.LOG_PREFIX + BluetoothActivity.class.getCanonicalName();
    private ListView bluetooth_list;
    private static final int REQUEST_CONTROL = 10000;
    private BleService mBleService;
    private boolean mIsBind;
    private ServiceConnection serviceConnection;
    List<Map<String, String>> bluetoothList;
    ActionBar actionBar;
    private boolean getAllPermissionSuccess = false;
    private static final int RC_HANDLE_BLUETOOTH = 1;
    private static final int RC_HANDLE_BLUETOOTH_ADMIN = 2;
    private static final int RC_HANDLE_ACCESS_COARSE_LOCATION = 3;

    private void addBluetooth(String name, String mac, String bonded){
        for(int i = 0; i < bluetoothList.size(); i++){
            Map<String, String> map = bluetoothList.get(i);
            String mac_local = map.get("mac");
            if(mac_local.equals(mac)) return;
        }
        Map<String, String> e = new HashMap<>();
        e.put("name", name);
        e.put("mac", mac);
        e.put("bonded", bonded);
        bluetoothList.add(e);
    }

    protected void toast(final String msg) {
        runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                }
            });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

        bluetooth_list = findViewById(R.id.bluetooth_list);
        actionBar = getSupportActionBar();
        if(actionBar != null){
            //actionBar.setHomeButtonEnabled(true);
            //actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setTitle("正在搜索附近的蓝牙...");
        }
        bluetoothList = new ArrayList<>();
        getAllPermission();
        start_control_activity("", "", "");
        Log.e(TAG, "oncreate finish");
    }

    private void init_bluetooth() {
        serviceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mBleService = ((BleService.LocalBinder) service).getService();
                //if (mBleService != null) mHandler.sendEmptyMessage(SERVICE_BIND);
                if (mBleService.initialize()) {
                    if (mBleService.enableBluetooth(true)) {
                        mBleService.setOnServicesDiscoveredListener(BluetoothActivity.this);
                        mBleService.getSupportedGattServices();
                        mBleService.setOnLeScanListener(BluetoothActivity.this);
                        mBleService.scanLeDevice(true, 20000);
                        Log.e(TAG, "mBleService was Connected");
                    }
                } else {
                    toast("蓝牙服务启动失败");
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                mBleService = null;
                mIsBind = false;
            }
        };
        doBindService();
    }

    @Override
    public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
        String mac = device.getAddress();
        //mac = mac.replace(":", "").toUpperCase();
        String  bonded;
        if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
            Log.e(TAG, device.getName() + ": " + mac);
            bonded = "已绑定";
        } else {
            Log.e(TAG, device.getName() + ": " + mac);
            bonded = "未绑定";
        }
        addBluetooth(device.getName(), mac, bonded);
        fillBluetoothInfo();
    }

    @Override
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        List<BluetoothGattService> services = gatt.getServices();
        if(services != null) {
            for(int i = 0; i < services.size(); i++){
                Log.e(TAG, "service " + i + " " + services.get(i).getUuid());
            }
        }
        Log.e(TAG, gatt.toString());
    }

    private void doBindService() {
        Intent serviceIntent = new Intent(this, BleService.class);
        bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    private void doUnBindService() {
        if (mIsBind) {
            unbindService(serviceConnection);
            mBleService = null;
            mIsBind = false;
        }
    }

    public class BluetoothReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Log.e(TAG, action);
            if (action.equals(BluetoothDevice.ACTION_FOUND)) {

                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                if (device != null && device.getName() != null && device.getName().startsWith("CRM508")) {
                    ParcelUuid[] parcelUuids = device.getUuids();
                    if (parcelUuids != null){
                        Log.e(TAG, "connect_bluetooth parcelUuids " + parcelUuids.length);
                    } else{
                        Log.e(TAG, "connect_bluetooth parcelUuids null");
                    }
                    //device.fetchUuidsWithSdp();
                    UUID MY_UUID = UUID.fromString("0000FE50-0000-1000-8000-00805F9B34FB");
                    UUID MY_UUID2 = UUID.fromString("00001800-0000-1000-8000-00805F9B34FB");
                    UUID MY_UUID3 = UUID.fromString("00001801-0000-1000-8000-00805F9B34FB");

                    try {
                        //BluetoothSocket btSocket = device.createInsecureRfcommSocketToServiceRecord(MY_UUID3);// commSocketToServiceRecord(MY_UUID1);
                        //btSocket.connect();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                String mac = device.getAddress();
                //mac = mac.replace(":", "").toUpperCase();
                String  bonded;
                if (device.getBondState() == BluetoothDevice.BOND_BONDED) {
                    Log.e(TAG, device.getName() + ": " + mac);
                    bonded = "已绑定";
                } else {
                    Log.e(TAG, device.getName() + ": " + mac);
                    bonded = "未绑定";
                }
                addBluetooth(device.getName(), mac, bonded);
                fillBluetoothInfo();
            } else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
                Log.e(TAG, "搜索完成");
                if(actionBar != null) actionBar.setTitle("搜索完成");
            }
        }

    }

    public void start_control_activity(String name, String mac, String bonded){
        doUnBindService();
        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtra("name", name);
        intent.putExtra("mac", mac);
        intent.putExtra("bonded", bonded);
        startActivityForResult(intent, REQUEST_CONTROL);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CONTROL) {
            if (resultCode == RESULT_OK) {
                Log.e(TAG, "MainActivity finish");
            } else {
                Log.e(TAG, "MainActivity failed");
            }
            doUnBindService();
        } else {
            Log.e(TAG, "Unknow error");
        }
    }

    private void fillBluetoothInfo(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                CustomAdapter customAdapter = new CustomAdapter(
                        BluetoothActivity.this, bluetoothList,
                        BluetoothActivity.this, 100,
                        0, null, null);
                bluetooth_list.setAdapter(customAdapter);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        fillBluetoothInfo();
        Log.e(TAG, "lifecycle: onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(getAllPermissionSuccess) {
            //init_bluetooth();
        }
        Log.e(TAG, "lifecycle: onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "lifecycle: onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.e(TAG, "lifecycle: onStop");
    }

    @Override
    protected void onDestroy() {
        Log.e(TAG, "lifecycle: onDestroy");
        doUnBindService();
        super.onDestroy();
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
        }
        return super.onKeyUp(keyCode, event);
    }

    private void getAllPermission(){
        int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH);
        if (rc != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "BLUETOOTH permission is not granted. Requesting permission");
            final String[] permissions = new String[]{Manifest.permission.BLUETOOTH};
            ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_BLUETOOTH);
            return;
        }

        rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN);
        if (rc != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "BLUETOOTH_ADMIN permission not granted. Requesting permission");
            final String[] permissions = new String[]{Manifest.permission.BLUETOOTH_ADMIN};
            ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_BLUETOOTH_ADMIN);
            return;
        }

        rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
        if (rc != PackageManager.PERMISSION_GRANTED) {
            Log.w(TAG, "ACCESS_COARSE_LOCATION permission not granted. Requesting permission");
            final String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION};
            ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_ACCESS_COARSE_LOCATION);
            return;
        }
        getAllPermissionSuccess = true;
        init_bluetooth();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (requestCode == RC_HANDLE_BLUETOOTH) {
                Log.e(TAG, "Get BLUETOOTH permission");
            } else if(requestCode == RC_HANDLE_BLUETOOTH_ADMIN) {
                Log.e(TAG, "Get BLUETOOTH_ADMIN permission");
            } else if (requestCode == RC_HANDLE_ACCESS_COARSE_LOCATION){
                Log.e(TAG, "Get ACCESS_COARSE_LOCATION permission");
            } else {
                Log.e(TAG, "Unknow permission");
            }
            getAllPermission();
        } else {
            String msg = "";
            if (requestCode == RC_HANDLE_BLUETOOTH) {
                msg = "获取蓝牙权限失败";
                Log.e(TAG, msg);
            } else if(requestCode == RC_HANDLE_BLUETOOTH_ADMIN) {
                msg = "获取蓝牙管理员权限失败";
                Log.e(TAG, msg);
            } else if (requestCode == RC_HANDLE_ACCESS_COARSE_LOCATION){
                msg = "获取位置权限失败";
                Log.e(TAG, msg);
            } else {
                msg = "获取权限失败";
                Log.e(TAG, msg);
            }
            toast(msg);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("");
            builder.setMessage(msg);
            builder.setPositiveButton("确定", mDlgClick);
            builder.show();
        }
    }

    private DialogInterface.OnClickListener mDlgClick = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            if (which == AlertDialog.BUTTON_POSITIVE) {
                //android.os.Process.killProcess(android.os.Process.myPid());
                finish();
            }
        }
    };
}
